package com.mifengkong.cygtools.jjcard;

import com.mifengkong.frtools.http.request.ApiException;
import com.mifengkong.frtools.util.FRString;

import io.reactivex.functions.Function;

/**
 * 变换: 将服务器返回的原始数据剥离成我们最终想要的数据
 * 将BaseResponse<T> 转换成 T
 */

public class HttpFunctionForCard<T> implements Function<BaseResponseForCard<T>, T> {
    public static final String DATA_AND_MESSAGE_NULL = "date and message is empty";

    @Override
    public T apply(BaseResponseForCard<T> response) throws Exception {
        if (!response.isCodeSuccess() || isNullObjectOrArray(response.getData())) {
            throw new ApiException(response.getCode(), response.getMessage(), response.getCode() == 0);
        }
        if (!response.isCodeSuccess()) {
            if (!FRString.isEmpty(response.getMessage())) {
                return (T) response.getMessage();
            }
            return (T) DATA_AND_MESSAGE_NULL;
        }

        return response.getData();
    }

    public boolean isNullObjectOrArray(Object object) {
        if (object == null) {
            return true;
        }
        return false;
    }
}